<template>
    <div class="ab-wrapper">
        <button v-if="isAttention" class="base-button" @click="unFocusEvent">取消关注</button>
        <button v-else class="base-button" @click="focusEvent">关注</button>
    </div>
</template>

<script>
    import {IO} from "../../../common/plus/io";

    export default {
        name: "AttentButton",
        props: {
            id: String
        },
        data() {
            return {
                isAttention: false
            };
        },
        created() {
            this.initAttention(this.id);
        },
        methods: {
            /*关注*/
            initAttention(id) {
                this.isAttention = this.$store.state.attentionModule.attentionList.includes(id);
            },
            focusEvent() {
                if (this.id) {
                    console.log('关注');
                    this.attentionFile(data => {
                        data.push(this.id);
                        return data;
                    }, '关注');
                }
            },
            unFocusEvent() {
                if (this.id) {
                    console.log('取消关注');
                    this.attentionFile(data => {
                        let index = data.indexOf(this.id);
                        if (index !== -1) {
                            data.splice(index, 1);
                        }
                        return data;
                    }, '取消');
                }
            },
            // 关注文件
            attentionFile(fn, msg) {
                if (this.$production && this.$store.state.plusAlready) {
                    const filename = 'attention.json';
                    IO.writeFile(filename, ({data, writer, error, mes}) => {
                        if (!error) {
                            if (data) {
                                const param = fn(data);
                                writer.onwrite = () => {
                                    this.$store.commit('setAttentionList', param);
                                    this.isAttention = !this.isAttention;
                                    // alert(`${msg}  成功`);
                                    console.log(`${msg}  成功`);
                                };
                                let str = JSON.stringify(param);
                                writer.seek(0);
                                writer.write(str);
                            } else {
                                alert(`${filename} 没有数据`)
                            }
                        } else {
                            alert(mes);
                        }
                    });
                }
            }
        }
    };
</script>

<style scoped lang="scss">
    .ab-wrapper {

    }
</style>
